package com.atguigu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class Flink01_Batch_WordCount {
    public static void main(String[] args) throws Exception {
        /**
         * spark中求WordCount逻辑
         * 1.创建Spark环境
         * 2.用读取文件的算子将文件中的数据读取到 RDD
         * 3.调用FlatMap算子 对数据进行转换 转换为Tuple2元组（单词，1）
         * 4.调用reduceBykey算子，先对相同单词的数据聚合到一快 然后根据reduceByKey中的逻辑做累加
         * 5.调用行动算子输出
         * 6.释放资源
         */

        //1.创建flink批处理环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //2.用读取文件的算子将文件中的数据读取到
        DataSource<String> dataSource = env.readTextFile("input/word.txt");

        //3.调用FlatMap算子 对数据进行转换 转换为Tuple2元组（单词，1）
        FlatMapOperator<String, Tuple2<String, Integer>> wordToOne = dataSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            /**
             *
             * @param value 传进来的数据
             * @param out 收集器 收集返回的数据 将数据发送至下游
             * @throws Exception
             */
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                //a.按照空格切分获取到每一个单词
                String[] words = value.split(" ");
                //b.遍历字符串数组获取到每一个单词
                for (String word : words) {
//                    Tuple2<String, Integer> tuple2 = new Tuple2<>(word, 1);
                    Tuple2<String, Integer> tuple2 = Tuple2.of(word, 1);
                    out.collect(tuple2);
                }
            }
        });

        //4.先对相同单词的数据聚合到一块
        UnsortedGrouping<Tuple2<String, Integer>> groupBy = wordToOne.groupBy(0);

        //5.做累加操作
        AggregateOperator<Tuple2<String, Integer>> sum = groupBy.sum(1);

        //6.打印到控制台
        sum.print();


    }
}
